<template>
  <el-card>
    <h2>团购管理</h2>
    <el-table :data="storeList" style="width: 100%">
      <el-table-column prop="storeName" label="门店名称" />
      <el-table-column prop="franchisee" label="加盟商" />
      <el-table-column prop="phone" label="电话" />
      <el-table-column prop="province" label="省份" />
      <el-table-column prop="address" label="地址" />
      <el-table-column v-if="userStore.roleCode == 3" prop="employee5Name" label="管理员工" />
      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button size="small" @click="viewDetail(row)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="门店详情" width="600px">
      <div v-if="detailData">
        <el-descriptions :column="2" border size="small">
          <el-descriptions-item label="门店ID">{{ detailData.storeId }}</el-descriptions-item>
          <el-descriptions-item label="门店名称">{{ detailData.storeName }}</el-descriptions-item>
          <el-descriptions-item label="加盟商">{{ detailData.franchisee }}</el-descriptions-item>
          <el-descriptions-item label="电话">{{ detailData.phone }}</el-descriptions-item>
          <el-descriptions-item label="省份">{{ detailData.province }}</el-descriptions-item>
          <el-descriptions-item label="地址">{{ detailData.address }}</el-descriptions-item>
          <el-descriptions-item label="状态">{{ detailData.status }}</el-descriptions-item>
        </el-descriptions>
        <h4 style="margin-top: 20px;">建店照片</h4>
        <div v-for="type in [1,4]" :key="type" style="margin-bottom: 12px;">
          <b>{{ photoTypeLabels[type] }}：</b>
          <template v-if="photoGroups[type] && photoGroups[type].length">
            <div v-for="photo in photoGroups[type]" :key="photo.photoId" style="margin-bottom: 8px;">
              <img :src="photo.photoPath" style="max-width: 200px; max-height: 120px; margin-right: 8px;" />
              <div style="margin-top: 4px; font-size: 12px; color: #666;">
                <span>平台ID: {{ photo.platformId || '-' }}</span>
                <span style="margin-left: 12px;">账号: {{ photo.platformAccount || '-' }}</span>
                <span style="margin-left: 12px;">密码: {{ photo.platformPassword || '-' }}</span>
              </div>
            </div>
          </template>
          <template v-else>
            <span>无</span>
          </template>
        </div>
      </div>
      <div v-else>暂无数据</div>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/user';
const userStore = useUserStore();
const storeList = ref([]);
const dialogVisible = ref(false);
const detailData = ref(null);
const photoTypeLabels = {
  0: '京东外卖',
  1: '美团团购',
  2: '美团外卖',
  3: '饿了么外卖',
  4: '抖音团购'
};
const photoGroups = ref({});

async function fetchStoreListForAdmin() {
  const res = await fetch(`http://121.43.176.9:8090/api/store/all-by-employee5`).then(r => r.json());
  if (res.code === 200) {
    const stores = res.data || [];
    // 批量获取员工姓名
    await Promise.all(stores.map(async (store) => {
      if (store.employee5Id) {
        const empRes = await fetch(`http://121.43.176.9:8090/api/employee/info?employeeId=${store.employee5Id}`).then(r => r.json());
        if (empRes.code === 200 && empRes.data && empRes.data.name) {
          store.employee5Name = empRes.data.name;
        } else {
          store.employee5Name = '';
        }
      } else {
        store.employee5Name = '';
      }
    }));
    storeList.value = stores;
  } else {
    storeList.value = [];
    ElMessage.error(res.msg || '获取门店失败');
  }
}

async function fetchStoreList() {
  const res = await fetch(`http://121.43.176.9:8090/api/store/by-employee5?employee5Id=${userStore.userId}`).then(r => r.json());
  if (res.code === 200) {
    storeList.value = res.data || [];
  } else {
    storeList.value = [];
    ElMessage.error(res.msg || '获取门店失败');
  }
}

async function checkAndFetchStoreList() {
  if (Number(userStore.roleCode) === 3) {
    // 管理员
    await fetchStoreListForAdmin();
  } else {
    // 其他员工，判断是否为5号员工
    const res = await fetch(`http://121.43.176.9:8090/api/employee/is-type5?employeeId=${userStore.userId}`).then(r => r.json());
    if (res.code === 200 && res.data === true) {
      await fetchStoreList();
    } else {
      storeList.value = [];
      ElMessage.error('您不是团购管理权限员工，无法查看门店');
    }
  }
}

async function viewDetail(row) {
  detailData.value = row;
  dialogVisible.value = true;
  // 获取建店照片
  photoGroups.value = {};
  const res = await fetch(`http://121.43.176.9:8090/api/store-setup-photos/by-store/${row.storeId}`).then(r => r.json());
  if (res.code === 200 && Array.isArray(res.data)) {
    // 按类型分组，存储完整的照片对象
    res.data.forEach(photo => {
      if (!photoGroups.value[photo.photoType]) {
        photoGroups.value[photo.photoType] = [];
      }
      photoGroups.value[photo.photoType].push(photo);
    });
  }
}

onMounted(() => {
  checkAndFetchStoreList();
});
</script> 